package com.aspectj.aop.aspects;

import com.aspectj.aop.annotation.ArgsNullCheck;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * desc   : 参数非空判断AOP
 * author : chendaning
 * date   : 6/11/21
 */
@Aspect
public class ArgsNullCheckAspect extends FatherAspect{
    private final String POINTCUT = "execution(@com.aspectj.aop.annotation.ArgsNullCheck * *(..))";

    @Pointcut(POINTCUT)
    public void onArgsNullCheckPointcut() {}

    /**
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("onArgsNullCheckPointcut() && @annotation(nullCheck)")
    public Object execute(ProceedingJoinPoint joinPoint, ArgsNullCheck nullCheck) throws Throwable {
        logger("exe ArgsNullCheck");

        if(nullCheck.args().length != 0) {
            Object[] objects = joinPoint.getArgs();
            for(int item: nullCheck.args()){
                if(item >= 0 && item < objects.length) {
                    if(objects[item] == null) {
                        logger("args position=" + item + " can not null!");
                        return null;
                    }
                }
            }
        }
        return joinPoint.proceed();
    }

}